'use client';

import { useEffect, useState } from 'react';
import api from '@/lib/api';

const TestApiComponent = () => {
  const [users, setUsers] = useState<any[]>([]);
  const [trades, setTrades] = useState<any[]>([]);
  const [markets, setMarkets] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const fetchData = async () => {
      try {
        setLoading(true);
        
        // 并行请求所有测试数据
        const [usersRes, tradesRes, marketsRes] = await Promise.all([
          api.user.getUsers(),
          api.trade.getTrades({ page: 1, limit: 5 }),
          api.market.getMarkets(),
        ]);

        setUsers(usersRes.data || []);
        setTrades(tradesRes.data?.list || []);
        setMarkets(marketsRes.data || []);
      } catch (err) {
        setError('获取数据失败，请检查API连接');
        console.error('API测试失败:', err);
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, []);

  if (loading) {
    return <div className="p-4 text-center">加载中...</div>;
  }

  if (error) {
    return <div className="p-4 text-center text-red-500">{error}</div>;
  }

  return (
    <div className="p-4 bg-gray-50 dark:bg-gray-800 rounded-lg">
      <h2 className="text-xl font-bold mb-4">API和Mock测试</h2>
      
      <div className="mb-6">
        <h3 className="text-lg font-semibold mb-2">用户数据 (Users)</h3>
        <div className="space-y-2">
          {users.length > 0 ? (
            users.map(user => (
              <div key={user.id} className="p-2 border rounded">
                {user.name} - {user.email}
              </div>
            ))
          ) : (
            <div>无用户数据</div>
          )}
        </div>
      </div>

      <div className="mb-6">
        <h3 className="text-lg font-semibold mb-2">交易数据 (Trades)</h3>
        <div className="space-y-2">
          {trades.length > 0 ? (
            trades.slice(0, 3).map(trade => (
              <div key={trade.id} className="p-2 border rounded">
                {trade.symbol} - {trade.side} - ${trade.price} x {trade.quantity}
              </div>
            ))
          ) : (
            <div>无交易数据</div>
          )}
        </div>
      </div>

      <div>
        <h3 className="text-lg font-semibold mb-2">市场数据 (Markets)</h3>
        <div className="space-y-2">
          {markets.length > 0 ? (
            markets.slice(0, 3).map((market, index) => (
              <div key={index} className="p-2 border rounded">
                {market.symbol} - ${market.price} ({market.change_24h > 0 ? '+' : ''}{market.change_24h}%)
              </div>
            ))
          ) : (
            <div>无市场数据</div>
          )}
        </div>
      </div>
    </div>
  );
};

export default TestApiComponent;